package com.shankungfu.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSON;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.shankungfu.GlobleConstant;
import com.shankungfu.MainApplication;
import com.shankungfu.R;
import com.shankungfu.adapter.MyExpandableListAdapter;
import com.shankungfu.bean.BaseBean;
import com.shankungfu.bean.CommentDataBean;
import com.shankungfu.bean.MessageBean;
import com.shankungfu.bean.PersonalLetterDataBean;
import com.shankungfu.bean.UserBean;
import com.shankungfu.main.CommentActivity;
import com.shankungfu.main.CommentReplyActivity;
import com.shankungfu.main.PersonalLetterAcitvity;
import com.shankungfu.util.MyAsyncHttpResponseHandler;
import com.shankungfu.util.TestUtils;
import com.shankungfu.util.WebService;

public class MessageFragment extends Fragment implements OnClickListener, OnGroupClickListener, OnChildClickListener {

	public static final String PERSONAL_LETTER_ID = "PERSONAL_LETTER_ID";
	public static final String USER_ID = "USER_ID";
	public static final String USER_IMG_URL = "USER_IMG_URL";
	private static final int data_success = 1;
	private static final int data_error = 2;

	private ExpandableListView expandable;
	private RelativeLayout progressBar;
	private List<PersonalLetterDataBean> list;
	private List<CommentDataBean> commentList;
	private MyExpandableListAdapter adapter;
	private ImageView head_refresh;

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);

			switch (msg.what) {
			case data_success:

				MessageBean bean = (MessageBean) msg.obj;
				
				list = bean.getPersonalLetterData();
				commentList = bean.getCommentData();

				ArrayList<Map<Object, Object>> groups = setGroup(
						Integer.valueOf(bean.getUnreadSys()),
						Integer.valueOf(bean.getUnreadInbox()),
						Integer.valueOf(bean.getUnreadReply()));

				adapter.setGroupList(groups);
				
				
				List<Object> childrensList = new ArrayList<Object>();
				childrensList.add(bean.getCommentData());
				childrensList.add(bean.getPersonalLetterData());
				childrensList.add(bean.getSystemData());
				
				
				adapter.setChildrens(childrensList);
				
				// list = inboxBean.getPersonalLetterData();
				// adapter.setPersonalLetterData(list);
				 adapter.notifyDataSetChanged();

				break;
			}

		}

	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.message_layout, null);
		initView(v);
		getData();
		updateForData();
		return v;
	}

	private void initView(View v) {
		expandable = (ExpandableListView) v.findViewById(R.id.expandable);
		progressBar = (RelativeLayout) v.findViewById(R.id.progressBar);
		head_refresh = (ImageView) getActivity()
				.findViewById(R.id.head_refresh);

		head_refresh.setOnClickListener(this);

		expandable.setGroupIndicator(null);
		
		List<Object> childerList = new ArrayList<Object>();
//		List<PersonalLetterDataBean> childrens = new ArrayList<PersonalLetterDataBean>();
//		childrens.add(new PersonalLetterDataBean());

		ArrayList<Map<Object, Object>> groupsList = new ArrayList<Map<Object, Object>>();
		adapter = new MyExpandableListAdapter(getActivity(), childerList,
				groupsList, MainApplication.getOptions());
		expandable.setOnChildClickListener(this);
		expandable.setOnGroupClickListener(this);
		expandable.setAdapter(adapter);
	}

	private ArrayList<Map<Object, Object>> setGroup(int xitongNum,
			int sixinNum, int pinglunNum) {
		ArrayList<Map<Object, Object>> groupsList = new ArrayList<Map<Object, Object>>();
		groupsList.add(setGroupData("评论消息", pinglunNum,
				R.drawable.message_pinglun));
		groupsList.add(setGroupData("私信", sixinNum, R.drawable.message_sixin));
		groupsList.add(setGroupData("系统消息", xitongNum,
				R.drawable.message_xitong));
		return groupsList;
	}

	private Map<Object, Object> setGroupData(String name, int number,
			int image_resource) {
		Map<Object, Object> map = new HashMap<Object, Object>();
		map.put("name", name);
		map.put("number", number);
		map.put("image", image_resource);
		return map;
	}

	private void getData() {
		WebService httpclient = new WebService();
		RequestParams params = new RequestParams();
		params.add("serviceId", "all_message");
		params.add("app_info", "shankungfu");
		params.add("flag", "2"); // 0未读 1 已读 2全部
		AsyncHttpResponseHandler responseHandler = new MyAsyncHttpResponseHandler() {
			@Override
			public void onSuccess(String content) {
				getSuccessData();
				if (!TextUtils.isEmpty(content)
						&& content.contains("\"result\":0")) {

					MessageBean bean = JSON.parseObject(content,
							MessageBean.class);
					Message msg = new Message();
					msg.what = data_success;
					msg.obj = bean;
					handler.sendMessage(msg);
				} else {
					handler.sendEmptyMessage(data_error);
				}
			}

			@Override
			public void onFailure(String content) {
			}

		};
		httpclient.request(GlobleConstant.ALL_MESSAGE, params, responseHandler);
	}

	private void updateForData() {
		progressBar.setVisibility(View.VISIBLE);
	}

	private void getSuccessData() {
		progressBar.setVisibility(View.GONE);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.head_refresh:
			getData();
			updateForData();
			break;
		}
	}

	@Override
	public boolean onChildClick(ExpandableListView parent, View v,
			int groupPosition, int childPosition, long id) {

		if (groupPosition == 0) {
			String comment_Id = commentList.get(childPosition).getComment_Id();
			
			Intent cIntent = new Intent(getActivity(), CommentActivity.class);
			cIntent.putExtra("project_id", comment_Id);
			startActivity(cIntent);
			return true;
		} else if (groupPosition == 1) {
			
			PersonalLetterDataBean letterBean = list.get(childPosition);
			Intent intent = new Intent(getActivity(), PersonalLetterAcitvity.class);
			intent.putExtra(USER_ID, letterBean.getUser_id());
			intent.putExtra(PERSONAL_LETTER_ID, letterBean.getPersonal_letter_Id());
			intent.putExtra(USER_IMG_URL, letterBean.getUser_img_url());
			getActivity().startActivity(intent);
			return true;
		}
		
		return false;
	}

	@Override
	public boolean onGroupClick(ExpandableListView parent, View v,
			int groupPosition, long id) {
		if (groupPosition == 0) {
			readData(4);
		} else if (groupPosition == 2) {
			readData(1);
		}
		return false;
	}
	
	/**
	 * 这里只处理 系统消息和评论，私信会在服务器自动处理
	 * @param notification_id
	 * @param type
	 */
	private void readData(final int type) {
		WebService httpclient = new WebService();
		RequestParams params = new RequestParams();
		params.add("serviceId", "message_read");
		params.add("type", "0"); 							// 0为全部标记已读，1为该条消息已读(type = 1,就不处理其他的数据)
		params.add("notification_id", "");    //(优先级低) 上面已经标记全部已读，因此不用处理这个
		params.add("type_for", type + ""); 					// 1为系统消息全部已读 4为问答消息全部已读 (为0 ，才会处理这个)
		MyAsyncHttpResponseHandler responseHandler = new MyAsyncHttpResponseHandler() {

			@Override
			public void onSuccess(String content) {
				TestUtils.logI("LogInActivity content " + content);
				if (!TextUtils.isEmpty(content)
						&& content.contains("\"result\":0")) {
					BaseBean userBean = JSON.parseObject(content,
							BaseBean.class);
					
					if (type == 1) {
						TestUtils.logI("评论消息全部已读");
					} else if (type == 4) {
						TestUtils.logI("系统消息全部已读");
					}
				} else {
				}
			}

			@Override
			public void onFailure(String content) {

			}
		};
		responseHandler.setShowNotNetToast(false);
		httpclient
				.request(GlobleConstant.MESSAGE_READ, params, responseHandler);

	}
}
